package com.haoran.dwz.service.impl;

import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.haoran.dwz.domain.entities.Menu;
import com.haoran.dwz.domain.entities.Role;
import com.haoran.dwz.repository.MenuRepository;
import com.haoran.dwz.service.MenuService;

@Service
public class MenuServiceImpl implements MenuService {
	
	@Autowired
	private MenuRepository  menuRepository;
	@Override
	public List<Menu> findAll() {
		List<Menu> list = menuRepository.findByParentIsNullOrderByOrderNumberAsc();
		for (Menu menu : list) {
			sortChildrenMenus(menu);
		}
		return list;
	}
	
	@Override
	public Collection<Menu> findAllByRole(Role defaultRole) {
		Set<Menu> list = defaultRole.getMenus();
		Menu.sort(list);
		for (Menu menu : list) {
			sortChildrenMenus(menu);
		}
		return list;
	}

	
	private void sortChildrenMenus(Menu menu) {
		Collection<Menu> children = menu.getChildren();
		if(children != null && !children.isEmpty()) {
			menu.setChildren(Menu.sort(children));
			for (Menu e : children) {
				sortChildrenMenus(e);
			}
		}
	}

	@Override
	@Transactional
	public void newAdd(Menu menu) {
		menuRepository.save(menu);
	}

	@Override
	public Menu findById(String id) {
		return menuRepository.findOne(id);
	}

	@Override
	public void update(Menu menu) {
		menuRepository.save(menu);
	}

}
